﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace AyuBookmark.WinForm.Dialogs
{
    /// <summary>
    /// 全局快捷搜索弹窗（支持快捷键呼出和结果导航）
    /// </summary>
    public partial class QuickSearchForm : Form
    {
        private TextBox txtSearch;
        private ListBox lstResults;
        private System.Windows.Forms.Timer searchTimer; // 明确指定Timer类型
        private List<QuickSearchItem> _allItems = new List<QuickSearchItem>();
        private const int MaxResults = 10;

        // 公共事件
        public event EventHandler<QuickSearchItem> ItemSelected;

        public QuickSearchForm()
        {
            InitializeComponent();
            SetupBehavior();
        }

        private void InitializeComponent()
        {
            // 窗体基础设置
            this.SuspendLayout();
            this.Text = "快速搜索";
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.None;
            this.ShowInTaskbar = false;
            this.TopMost = true;
            this.Size = new Size(450, 400);
            this.BackColor = Color.FromArgb(245, 245, 245);
            this.Padding = new Padding(5);
            this.KeyPreview = true;

            // 搜索框
            this.txtSearch = new TextBox();
            this.txtSearch.Dock = DockStyle.Top;
            this.txtSearch.Font = new Font("Microsoft YaHei", 12f);
            this.txtSearch.BorderStyle = BorderStyle.FixedSingle;
            this.txtSearch.Margin = new Padding(0, 0, 0, 5);
            this.txtSearch.TabIndex = 0;

            // 搜索结果列表
            this.lstResults = new ListBox();
            this.lstResults.Dock = DockStyle.Fill;
            this.lstResults.Font = new Font("Microsoft YaHei", 10f);
            this.lstResults.BorderStyle = BorderStyle.None;
            this.lstResults.DrawMode = DrawMode.OwnerDrawVariable;
            this.lstResults.ItemHeight = 30;
            this.lstResults.DrawItem += OnDrawResultItem;
            this.lstResults.MeasureItem += OnMeasureResultItem;
            this.lstResults.DoubleClick += (s, e) => SelectCurrentItem();

            // 搜索延迟计时器（明确使用Windows.Forms.Timer）
            this.searchTimer = new System.Windows.Forms.Timer();
            this.searchTimer.Interval = 200;
            this.searchTimer.Tick += (s, e) => PerformSearch();

            // 添加控件
            this.Controls.Add(this.lstResults);
            this.Controls.Add(this.txtSearch);

            this.ResumeLayout(false);
        }

        private void SetupBehavior()
        {
            // 键盘事件处理
            this.txtSearch.KeyDown += (s, e) =>
            {
                switch (e.KeyCode)
                {
                    case Keys.Escape:
                        this.Close();
                        break;
                    case Keys.Up:
                        if (lstResults.Items.Count > 0)
                        {
                            lstResults.SelectedIndex = Math.Max(0, lstResults.SelectedIndex - 1);
                            e.Handled = true;
                        }
                        break;
                    case Keys.Down:
                        if (lstResults.Items.Count > 0)
                        {
                            lstResults.SelectedIndex = Math.Min(lstResults.Items.Count - 1,
                                lstResults.SelectedIndex + 1);
                            e.Handled = true;
                        }
                        break;
                    case Keys.Enter:
                        SelectCurrentItem();
                        break;
                }
            };

            // 文本变化触发搜索
            this.txtSearch.TextChanged += (s, e) =>
            {
                searchTimer.Stop();
                searchTimer.Start();
            };

            // 失去焦点关闭窗口
            this.Deactivate += (s, e) => this.Close();
        }

        /// <summary>
        /// 设置可搜索的数据源
        /// </summary>
        public void SetSearchSource(IEnumerable<QuickSearchItem> items)
        {
            this._allItems = new List<QuickSearchItem>(items);
        }

        /// <summary>
        /// 显示搜索窗口（相对于指定控件定位）
        /// </summary>
        public void Show(Control relativeTo)
        {
            if (relativeTo != null)
            {
                Point location = relativeTo.PointToScreen(new Point(0, relativeTo.Height));
                this.Location = location;
                this.Width = relativeTo.Width;
            }

            base.Show();
            this.txtSearch.Focus();
        }

        private void PerformSearch()
        {
            searchTimer.Stop();

            string keyword = this.txtSearch.Text.Trim();
            if (string.IsNullOrEmpty(keyword))
            {
                lstResults.Items.Clear();
                return;
            }

            var results = new List<QuickSearchItem>();
            foreach (var item in _allItems)
            {
                // 简单匹配逻辑（实际项目可改为模糊匹配）
                if (item.Title.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
                    (item.Description?.Contains(keyword, StringComparison.OrdinalIgnoreCase) ?? false))
                {
                    results.Add(item);
                    if (results.Count >= MaxResults) break;
                }
            }

            lstResults.BeginUpdate();
            lstResults.Items.Clear();
            lstResults.Items.AddRange(results.ToArray());
            if (lstResults.Items.Count > 0)
            {
                lstResults.SelectedIndex = 0;
            }
            lstResults.EndUpdate();
        }

        private void SelectCurrentItem()
        {
            if (lstResults.SelectedItem is QuickSearchItem selectedItem)
            {
                ItemSelected?.Invoke(this, selectedItem);
                this.Close();
            }
        }

        #region 自定义绘制
        private void OnMeasureResultItem(object sender, MeasureItemEventArgs e)
        {
            if (e.Index < 0) return;

            var item = (QuickSearchItem)lstResults.Items[e.Index];
            e.ItemHeight = string.IsNullOrEmpty(item.Description) ? 30 : 50;
        }

        private void OnDrawResultItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0) return;

            var item = (QuickSearchItem)lstResults.Items[e.Index];
            bool isSelected = (e.State & DrawItemState.Selected) == DrawItemState.Selected;

            // 背景色
            using (var backBrush = new SolidBrush(isSelected ?
                Color.FromArgb(230, 240, 250) : Color.White))
            {
                e.Graphics.FillRectangle(backBrush, e.Bounds);
            }

            // 标题
            using (var titleBrush = new SolidBrush(isSelected ?
                Color.FromArgb(0, 120, 215) : Color.Black))
            {
                var titleFont = new Font(e.Font, FontStyle.Bold);
                e.Graphics.DrawString(item.Title, titleFont, titleBrush,
                    new Rectangle(e.Bounds.X + 5, e.Bounds.Y + 3, e.Bounds.Width - 10, 20));
            }

            // 描述（如果有）
            if (!string.IsNullOrEmpty(item.Description))
            {
                using (var descBrush = new SolidBrush(isSelected ?
                    Color.FromArgb(0, 120, 215) : Color.Gray))
                {
                    e.Graphics.DrawString(item.Description, e.Font, descBrush,
                        new Rectangle(e.Bounds.X + 5, e.Bounds.Y + 25, e.Bounds.Width - 10, 20));
                }
            }

            // 分隔线
            using (var pen = new Pen(Color.FromArgb(240, 240, 240)))
            {
                e.Graphics.DrawLine(pen, e.Bounds.X, e.Bounds.Bottom - 1,
                    e.Bounds.Right, e.Bounds.Bottom - 1);
            }
        }
        #endregion

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            // 绘制边框
            using (var pen = new Pen(Color.FromArgb(200, 200, 200)))
            {
                e.Graphics.DrawRectangle(pen, 0, 0, this.Width - 1, this.Height - 1);
            }
        }

        public class QuickSearchItem
        {
            public string Title { get; set; }
            public string Description { get; set; }
            public object Tag { get; set; } // 关联数据对象
        }

        public static void ShowQuickSearch(IWin32Window owner,
            IEnumerable<QuickSearchItem> items,
            Action<QuickSearchItem> callback)
        {
            using (var form = new QuickSearchForm())
            {
                form.SetSearchSource(items);
                form.ItemSelected += (s, e) => callback?.Invoke(e);
                form.ShowDialog(owner);
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                searchTimer?.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}